package com.carrot.newsgallery.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.carrot.newsgallery.common.R;
import com.carrot.newsgallery.entity.NewsFavor;
import com.carrot.newsgallery.entity.UserFile;
import com.carrot.newsgallery.entity.UserInfo;
import com.carrot.newsgallery.service.NewsFavorService;
import com.carrot.newsgallery.service.UserFileService;
import com.carrot.newsgallery.service.UserInfoService;
import com.carrot.newsgallery.utils.HttpUtil;
import com.carrot.newsgallery.utils.ReturnCode;
import com.carrot.newsgallery.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Api(value = "笔记中文件上传")
public class UserFileController {

    @Value("${path.root-path}")
    private String rootPath;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserFileService userFileService;

    @Autowired
    private NewsFavorService newsFavorService;

    /**
     *
     * @param request
     * @param uploadFile
     * @return R中的data为一个字符串,包含的内容是请求该文件的命令
     * @throws IOException
     */
    @PostMapping
    @ApiOperation("上传文件")
    public R upload(HttpServletRequest request, @RequestParam MultipartFile uploadFile,
                    @RequestParam int newsFavorId) throws IOException {
        String token = HttpUtil.getToken(request);
        TokenUtil tokenUtil = new TokenUtil();
        UserInfo user = tokenUtil.getUser(token);

        //判断文件是否为空
        if (uploadFile.isEmpty()){
            return R.fail(ReturnCode.DATA_ERROR,"请勿上传空文件");
        }

        //设置文件上传路径
        String uuid = user.getUuid();
        String dirPath = "/data/user/" + uuid ;
        String originalFilename = uploadFile.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString().replaceAll("-", "")+fileExtension;

        File file = new File(dirPath + "/" +filename);
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        uploadFile.transferTo(file);

        //相关信息载入数据库
        UserFile userFile = new UserFile();
        userFile.setFileName(filename);
        userFile.setPath(dirPath);
        userFile.setUserId(user.getUserInfoId());
        userFile.setFavorId(newsFavorId);

        if (userFileService.save(userFile))
            return R.success(rootPath+"/file/"+uuid+"/"+filename,"文件上传成功");
        else
            return R.fail(ReturnCode.SERVER_ERROR,"服务器异常,请稍后重试");
    }

    @GetMapping("/{uuid}/{filename}")
    @ApiOperation("下载文件")
    public R download(HttpServletRequest request, HttpServletResponse response,
                      @PathVariable String uuid, @PathVariable String filename){
        String token = HttpUtil.getToken(request);
        TokenUtil tokenUtil = new TokenUtil();
        UserInfo user = tokenUtil.getUser(token);
        String userUuid = user.getUuid();

        //如果userUuid和请求的目标文件的所属用户的uuid不同,那么就要先查数据库,看该图片所归属的收藏笔记是否处于公开状态
        //获取uuid对应的数据库记录
        UserFile userFile = userFileService.getByFileName(filename);
        if (!userUuid.equals(uuid)){
            //根据favorid查询是否公开
            NewsFavor newsFavor = newsFavorService.getById(userFile.getFavorId());
            //未公开则报错
            if (newsFavor.getIsShared() == 0)
                return R.fail(ReturnCode.USER_ILLEGAL_OPERATION,"非法请求");
        }
        //可以返回该图片
        File file = new File(userFile.getPath() + filename);
        try {
            ServletOutputStream os = response.getOutputStream();
            response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
            response.setContentType("application/octet-stream");
            os.write(FileUtils.readFileToByteArray(file));
            os.flush();
            os.close();
        } catch (Exception exception){
            return R.fail(ReturnCode.SERVER_ERROR,"服务器异常,请稍后重试");
        }
        return R.success(null,"请求成功");
    }
}
